package teacherstudent;

import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

public class StudentDaoImpl implements StudentDao{

	private List<Student> students;
	
	public StudentDaoImpl(){
		students = new LinkedList<>();
	}
	
	@Override
	public boolean insert(Student t) {
		// 如果集合中包含t对象，那么就不添加此学生,底层调用t.equals(ele)
		if (students.contains(t)) {
			return false;
		}
		return students.add(t);
	}

	@Override
	public boolean update(Student t) {
		// 如果集合中包含t对象，那么就更新此人,底层调用t.equals(ele)
		int index = students.indexOf(t);
		if (index == -1) {
			return false;
		}else {
			students.set(index, t);
			return true;
		}
	}

	@Override
	public boolean delete(int id) {
		Iterator<Student> it = students.iterator();
		while(it.hasNext()) {
			Student stu = it.next();
			if (stu.getStudentId() == id) {
				// 迭代器在迭代的过程中可以直接删除元素
				it.remove();
				return true;
			}
		}
		return false;
	}

	
	@Override
	public Student selectById(int id) {
		
		for(Student s : students) {
			if (s.getStudentId() == id) {
				return s;
			}
		}
		return null;
	}

	@Override
	public List<Student> selectAll() {
		List<Student> copy = new LinkedList<>(students);
		return copy;
	}

	@Override
	public List<Student> sortByScoreDesc() {
		List<Student> copy = new LinkedList<>(students);
		// 比较器
		copy.sort(new Comparator<Student>() {
			@Override
			public int compare(Student o1, Student o2) {
				//     后-前  从大到小
				return o2.getStudentScore() - o1.getStudentScore();
			}
		});
		return copy;
	}
}
